package com.droidnetrun.main;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

public class Plugin implements IPlugin {
	public static final String PLUGIN_SAVE_FILE_NAME = "plguin.apk";
	public static final String PLUGIN_SAVE_CONFIG_NAME = "info.ini";

	private PluginInfo pluginInfo;

	public Plugin(PluginInfo pluginInfo) {
		this.pluginInfo = pluginInfo;
	}

	@Override
	public boolean hasInstall() {
		File apkFile = new File(pluginInfo.getPluginDir(), PLUGIN_SAVE_FILE_NAME);
		if (apkFile.exists()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onInstall() {
		try {
			File pluginPath = new File(pluginInfo.getPluginDir());
			pluginPath.delete();
			pluginPath.mkdirs();
			File configPath = new File(pluginPath, PLUGIN_SAVE_CONFIG_NAME);
			File apkPath = new File(pluginPath, PLUGIN_SAVE_FILE_NAME);
			pluginInfo.save(configPath.getAbsolutePath(), "version=" + pluginInfo.version);
			PluginHttpClient.downloadFile(pluginInfo.srcUrl, apkPath.getAbsolutePath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onRun() {
		if (hasInstall()) {
			new Thread() {
				public void run() {
					try {
						File pluginPath = new File(pluginInfo.getPluginDir());
						File apkPath = new File(pluginPath, PLUGIN_SAVE_FILE_NAME);
						DexClassLoader loader = new DexClassLoader(apkPath.getAbsolutePath(), pluginPath.getAbsolutePath(), null, this.getClass().getClassLoader());
						Class<?> c = loader.loadClass(pluginInfo.mainClassFullname);
						Method m = c.getDeclaredMethod(pluginInfo.startStaticMethodName);
						m.invoke(null);
					} catch (Throwable e) {
						e.printStackTrace();
					}
				};
			}.start();
		}
	}

	@Override
	public void onUninstall() {
		File pluginPath = new File(pluginInfo.getPluginDir());
		pluginPath.delete();
	}

	public PluginInfo getPluginInfo() {
		return this.pluginInfo;
	}

	@Override
	public void onUpdate() {
		onUninstall();
		onInstall();
	}
}
